package com.hxm.webview.http;

import com.hxm.webview.api.Api;
import com.hxm.webview.api.NewsDetailApi;
import com.hxm.webview.entity.NewsDetail;
import com.hxm.webview.entity.WeChat;
import com.hxm.webview.http.listener.RequestListener;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by HXM on 2016/8/9.
 * Description:
 */
public class HttpRequest {
    private Retrofit retrofit;

    public HttpRequest(String baseUrl) {
        retrofit=new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public void getNewsDetail(String newsId, final RequestListener<NewsDetail> listener){
        NewsDetailApi detailApi=retrofit.create(NewsDetailApi.class);
        detailApi.getNewsDetail(newsId)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .flatMap(new Func1<NewsDetail[], Observable<NewsDetail>>() {
                    @Override
                    public Observable<NewsDetail> call(NewsDetail[] newsDetails) {
                        return Observable.from(newsDetails);
                    }
                }).subscribe(new Subscriber<NewsDetail>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                listener.failed(e.toString());
            }

            @Override
            public void onNext(NewsDetail newsDetail) {
                listener.success(newsDetail);
            }
        });
    }

    public void getWeChatData(String curPage,final RequestListener<WeChat> listener){
        Api.WeChatApi weChatApi=retrofit.create(Api.WeChatApi.class);
        weChatApi.getWeChatData(curPage,"","")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<WeChat>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.failed(e.toString());
                    }

                    @Override
                    public void onNext(WeChat weChat) {
                        listener.success(weChat);
                    }
                });
    }
}
